import jwt
import datetime


header = {
    'alg': 'HS256',
    'typ': 'JWT'
}

SECRET_KEY = '123123'


class ToolJWT:
    def gettoken(self, user):
        payload = {
            'userid': user.get("id"),
            'username': user.get("username", ""),
            'exp': datetime.datetime.now()+datetime.timedelta(hours=3)
        }
        return jwt.encode(payload, SECRET_KEY, algorithm='HS256', headers=header)

    def checktoken(self, token):
        try:
            payload = jwt.decode(token, SECRET_KEY, algorithms=['HS256'], headers=header)
            return payload
        except jwt.ExpiredSignatureError:
            raise Exception('token过期')
        except jwt.InvalidTokenError:
            raise Exception('token无效')

# token="eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyaWQiOjIsInVzZXJuYW1lIjoicXFzIiwiZXhwIjoxNzMwMzE0ODYwfQ.2R78_Qrn8revFQt9ZEKdeRkqyRxGfEN_gTgdD6e_Rag"


# tool = ToolJWT()
# print(tool.gettoken({'id': 2, 'username': 'qqs'}))
# print(tool.checktoken(token))
tooljwt = ToolJWT()
